package com.lantian.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.lantian.oss.service.FileService;
import com.lantian.oss.utils.ConstanPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @name:
 * @description: 文件上传业务
 * @author: meet
 * @create: 2020-04-30 17:30
 */
@Service
public class FileServiceImpl implements FileService {

    private static String TYPESTR[] = {".png", ".jpg", ".bmp", ".gif", ".jpeg"};

    @Override
    public String upload(MultipartFile file) {

        String url = null;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClient(
                ConstanPropertiesUtil.END_POINT,
                ConstanPropertiesUtil.ACCESS_KEY_ID,
                ConstanPropertiesUtil.ACCESS_KEY_SECRET);
        try {
            //判断后缀格式
            boolean flag = false;
            for (String type : TYPESTR) {
                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                    flag = true;
                    break;
                }
            }
            if(!flag){
                return "图片格式不正确";
            }
            //判断文件内容
            BufferedImage imageIO = ImageIO.read(file.getInputStream());
            if (imageIO != null) {
                System.err.println(String.valueOf(imageIO.getHeight()));
                System.err.println(String.valueOf(imageIO.getWidth()));
            } else {
                return "文件内容不正确";
            }
            // 上传文件流。
            //设置文件名称，路径
            String filename = file.getOriginalFilename();
            String ext = filename.substring(filename.lastIndexOf("."));

            String newName = UUID.randomUUID().toString() + ext;
            String dataPath = new DateTime().toString("yyyy/MM/dd");

            String urlPath = ConstanPropertiesUtil.FILE_HOST + "/" + dataPath + "/" + newName;

            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ConstanPropertiesUtil.BUCKET_NAME, urlPath, inputStream);

            url = "https://" + ConstanPropertiesUtil.BUCKET_NAME + "." + ConstanPropertiesUtil.END_POINT + "/" + urlPath;

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return url;
    }
}
